package com.sdses.weather.config;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class WeatherConfigRegistry {

    private final WeatherProviderProperties properties;
    private final Map<String, WeatherProviderProperties.ReqRespConfig> requestURIConfigMap = new HashMap<>();

    @PostConstruct
    public void init() {
        requestURIConfigMap.clear();
        String appCode = properties.getAppCode();
        for (WeatherProviderProperties.ReqRespConfig cfg : properties.getProviders()) {
            try {

                String[] parts = cfg.getClassPath().split("\\$");
                String contextClassPath = StrUtil.isNotBlank(cfg.getContextClassPath()) ? cfg.getContextClassPath() : parts[0];

                // 🔍 通过类名反射加载 Class
                Class<?> clazz = Class.forName(cfg.getClassPath());
                Class<?> contextClass = Class.forName(contextClassPath);

                WeatherProviderProperties.ReqRespConfig config = new WeatherProviderProperties.ReqRespConfig(
                        cfg.getRequestURI(),
                        cfg.getTtl(),
                        cfg.getProvider(),
                        cfg.getType(),
                        cfg.getUrl(),
                        cfg.getMethod(),
                        cfg.getToken(),
                        clazz,
                        contextClass,
                        appCode
                );

                requestURIConfigMap.put(buildKey(cfg.getProvider(), StrUtil.equals(cfg.getType().split("-")[1], "city"), config.getRequestURI()), config);
                log.info("已加载厂商配置: {} | {} | {}", cfg.getProvider(), cfg.getType(), cfg.getUrl());
            } catch (ClassNotFoundException e) {
                log.error("映射类未找到: {}", cfg.getClassPath(), e);
            }
        }
    }

    public WeatherProviderProperties.ReqRespConfig getRequestURIConfigMap(String provider, boolean isByCity, String requestURI) {
        return requestURIConfigMap.get(buildKey(provider, isByCity, requestURI));
    }

    private String buildKey(String provider, boolean isByCity, String requestType) {
        return (provider + ":" + getRequestType(isByCity) + ":" + requestType).toLowerCase();
    }

    public String getRequestType(boolean isByCity) {
        return isByCity ? "city" : "location";
    }
}